import 'package:aichat_flutter_wallet/module/module_browser/provider/browser_proviser.dart';
import 'package:aichat_flutter_wallet/module/module_browser/widget/browser_fail.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_util/lib_util.dart';
import 'package:lib_util/log/log.dart';

import '../../../kai_print.dart';

class WebPage extends StatefulWidget {
  WebPage({super.key, this.url = 'https://baidu.com'});
  String? url;

  @override
  State<WebPage> createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  final GlobalKey webViewKey = GlobalKey();
  InAppWebViewController? webViewController;

  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
          useShouldOverrideUrlLoading: true, mediaPlaybackRequiresUserGesture: false, transparentBackground: true),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  // 下拉控制
  late PullToRefreshController pullToRefreshController;
  bool isShowDialog = false;
  bool isLoadSuccess = true;
  bool isFailed = false;

  void colseDialog() {
    if (isShowDialog) {
      setState(() {
        isShowDialog = false;
      });
      // BrowserProvider.close();
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    pullToRefreshController = PullToRefreshController(
      options: PullToRefreshOptions(
          // color: '#8667FE'.toColor(),
          color: AppColors.c_8667FE),
      onRefresh: () async {},
    );
  }

  @override
  void dispose() {
    webViewController = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            Container(
              height: 44.w,
              padding: EdgeInsets.only(left: 20.w, right: 15.w),
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      Navigator.of(context).pop();
                    },
                    child: Image(
                      image: AssetImage('assets/images/dapp/back.png'),
                      height: 20.w,
                      width: 20.w,
                    ),
                  ),
                  SizedBox(
                    width: 10.w,
                  ),
                  SizedBox(
                    width: 5.w,
                  ),
                  Expanded(
                    child: Container(
                      height: 34.w,
                      padding: EdgeInsets.symmetric(horizontal: 15.w),
                      decoration: BoxDecoration(borderRadius: BorderRadius.circular(10.w), color: AppColors.c_F6F6F6),
                      child: Row(
                        children: [
                          Image(
                            image: AssetImage('assets/images/dapp/lock.png'),
                            height: 12.w,
                            width: 12.w,
                          ),
                          SizedBox(
                            width: 7.w,
                          ),
                          Expanded(
                            child: GestureDetector(
                              child: Text(
                                widget.url!,
                                style: TextStyle(
                                  overflow: TextOverflow.ellipsis,
                                ),
                                maxLines: 1,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 10.w,
                  ),
                  GestureDetector(
                    onTap: () {
                    },
                    child: Image(
                      image: AssetImage('assets/images/dapp/browser.png'),
                      height: 30.w,
                      width: 30.w,
                    ),
                  )
                ],
              ),
            ),
            Expanded(child: Consumer<BrowserProvider>(builder: (c, browser, child) {
              bool isFirstLoad = false;
              return IndexedStack(
                index: isFailed == false ? 0 : 1,
                children: [
                  Column(
                    children: [
                      Visibility(
                          visible: browser.progress < 1,
                          child: SizedBox(
                            height: 2.w,
                            child: LinearProgressIndicator(
                              backgroundColor: Colors.transparent,
                              color: Color.fromRGBO(134, 103, 254, 1),
                              value: browser.progress,
                            ),
                          )),
                      Visibility(
                          visible: browser.progress >= 1,
                          child: Container(
                            height: 2.w,
                          )),
                      Expanded(
                          child: SingleChildScrollView(
                              child: SizedBox(
                                  height: MediaQuery.of(context).size.height - 88 - MediaQuery.of(context).padding.top,
                                  child: InAppWebView(
                                    key: webViewKey,
                                    initialOptions: options,
                                    initialUrlRequest: URLRequest(url: Uri.parse(widget.url!)),
                                    pullToRefreshController: pullToRefreshController,
                                    shouldOverrideUrlLoading: (controller, navigationAction) async {
                                      var uri = navigationAction.request.url!;
                                      if (!["http", "https", "file", "chrome", "data", "javascript", "about"]
                                          .contains(uri.scheme)) {
                                        return NavigationActionPolicy.CANCEL;
                                      }

                                      return NavigationActionPolicy.ALLOW;
                                    },
                                    onWebViewCreated: (controller) {
                                      webViewController = controller;
                                      browser.initController(controller, context);
                                    },
                                    onLoadStop: (controller, url) async {
                                      try {
                                        if (isFirstLoad) {
                                          return;
                                        }
                                        isFirstLoad = true;
                                        // 避免加载失败也会保存
                                      } catch (e) {
                                        kaiPrint('error:${e}');
                                      } finally {
                                        isFirstLoad = false;
                                      }
                                    },
                                    onLoadError: (controller, url, code, message) {
                                      Log.logger.e('错误');
                                      if (code < 0 && isFailed == false) {
                                        setState(() {
                                          isFailed = true;
                                        });
                                        return;
                                      }
                                    },
                                    onProgressChanged: (controller, progress) {
                                      if (progress < 10 || (browser.progress >= 1 && progress >= 100)) {
                                        return;
                                      }
                                      Log.logger.e('progress ------${progress}');
                                      browser.setProgress(progress / 100);
                                    },
                                    onConsoleMessage: (controller, consoleMessage) {
                                      Log.logger.d(consoleMessage.message);
                                    },
                                  ))))
                    ],
                  ),
                  BrowserFail(callBack: () {
                    setState(() {
                      isFailed = false;
                    });
                  }),
                ],
              );
            })),
          ],
        ),
      ),
    );
  }
}
